<?php

namespace Admin\Controller;

use Admin\Model\SysAccountModel;
use Admin\Model\UserModel;
use Admin\Model\UserAccountModel;

class OperatingController extends AdminController {

    public function index() {

        $cpage = (int)$_GET['p'] > 0 ? (int)$_GET['p'] : 1;
        $where = [];
        $nickname = I('nickname', '', 'addslashes,trim');
        $mobile = I('mobile', '', 'addslashes,trim');
        if (empty($this->users)) {
            $this->getAllUsers();
        }
        if (!empty($nickname)) {
            $user_id = 0;
            foreach ($this->users as $user) {
                if ($user['nickname'] == $nickname) {
                    $user_id = $user['id'];
                    break;
                }
            }
            $where['user_id'] = $user_id;
        }

        if (!empty($mobile)) {
            $where['mobile'] = $mobile;
        }

        $Operations = M('OperationsInfo');
        $result = $Operations->where($where)->order('id DESC')->page($cpage, $this->page_size)->select();

        $count = $Operations->where($where)->count();
        $Page = new \Think\Page($count, $this->page_size);

        $this->assign([
            'result' => $result,
            'page' => $Page->show(),
            'users' => $this->users,
        ]);

        $this->display();
    }

    public function fail() {
        $id = I('id', 0, 'intval');
        if (empty($id)) {
            $this->error('参数错误');
            return;
        }
        $info = M('OperationsInfo')->find($id);
        if (empty($info)) {
            $this->error('申请记录不存在');
            return;
        }

        if ($info['status'] != 0) {
            $this->error('该申请已处理');
            return;
        }

        if (IS_POST) {
            $msg = I('post.refuse_msg', '', 'trim,addslashes');
            if (empty($msg)) {
                $this->error('请填写拒绝的理由');
                return;
            }

            $result = M('OperationsInfo')->where(['id' => $info['id']])->data([
                'deal_at' => time(),
                'checker' => $this->admin_info['username'],
                'status' => 1,
                'refuse_msg' => $msg,
            ])->save();

            if ($result !== false) {
                $this->success('操作成功');
            }

            $this->error('操作失败');

        } else {
            $this->assign([
                'info' => $info,
            ]);
            $this->display();
        }
    }

    /**
     * 确认通过运营中心申请
     */
    public function ok() {
        $id = I('id', 0, 'intval');
        if (empty($id)) {
            return $this->error('参数错误');
        }
        $Op = M('OperationsInfo');
        $info = $Op->where(['id' => $id])->find();
        if (empty($info)) {
            return $this->error('申请记录不存在');
        }

        /**
         * 检查用户是否满足申请运营中心条件
         * 1/激活四个（包括）以上的下级会员
         * 2/报单金额最低50000
         */
        if ($info['amount'] < (float)$this->setting['min_user_operations_amount']) {
            return $this->error('没有满足申请运营中心的条件:代理金额最低' . $this->setting['min_user_operations_amount']);
        }

        $activer = M('User')->where(['id' => $info['user_id']])->find();
        if (empty($activer)) {
            return $this->error('ID是' . $info['user_id'] . '用户不存在');
        }

        if (in_array($activer['identity'], [UserModel::USER_SUPPER_SUPPLIER, UserModel::USER_SUPPLIER])) {
            return $this->error('该用户已经是运营中心身份，不需要重复申请');
        }

        $childCounts = M('User')->field('id')->where(
            [
                'inviter' => $info['user_id'],
                'identity' => ['neq', 0]
            ]
        )->count();

        if ($childCounts < (int)$this->setting['min_operations_count']) {
            return $this->error('没有满足申请运营中心的条件:最少激活' . $this->setting['min_operations_count'] . '个用户');
        }

        /*
         * 检查代申请的运营中心是否账户余额是否足够
         * 待申请人的身份信息验证，是否是一条线运营中心
         * 不足提示错误
        */
        $parents = $this->getParents($info['user_id']);
        if (!isset($parents[$info['applicant_id']])) {
            return $this->error('运营中心和用户不是一条线的关系，无法代申请');
        }

        $operation = M('User')->alias('A')
            ->join(C('DB_PREFIX') . 'user_wealth as B ON A.id = B.user_id', 'left')
            ->where(['A.id' => $info['applicant_id']])->find();
        if (empty($operation)) {
            return $this->error('运营中心不存在');
        }

        if ($operation['identity'] != UserModel::USER_SUPPLIER && $operation['identity'] != UserModel::USER_SUPPER_SUPPLIER) {
            return $this->error($operation['nickname'] . '不是运营中心身份，不能代申请运营中心');
        }

        /**
         * 根据支付方式计算出所需要的现金和积分
         */

        $need_balance = 0;  //需要的现金
        $need_integral = 0; //需要的积分
        if ($info['pay_type'] == 1) {
            $need_balance = $info['amount'];
        } else {
            $need_balance = sprintf('%.2f', (float)$this->setting['pay_balance_percent'] / 100) * (float)$info['amount'];
            $need_integral = (float)$info['amount'] - $need_balance;
        }

        if ($operation['integral'] < $need_integral) {
            return $this->error('需要支付积分' . $need_integral . '，运营中心【' . $operation['nickname'] . '】的积分不足');
        }

        if ($operation['balance'] < $need_balance) {
            return $this->error('需要支付现金' . $need_balance . '，运营中心【' . $operation['nickname'] . '】余额不足');
        }

        /**
         * 余额足够，扣除对应的现金[和积分]，写入代申请运营中心流水日志
         * 写入系统流水日志记录
         */
        M()->startTrans();

        try {
            //扣除现金和余额
            $unstore = $operation['unstore_integral'] > $need_integral ? $need_integral : $operation['unstore_integral'];
            M('UserWealth')->where(['user_id' => $operation['id']])->save([
                'integral' => ['exp', "integral-{$need_integral}"],
                'unstore_integral' => ['exp', "unstore_integral-{$unstore}"],
                'balance' => ['exp', "balance-{$need_balance}"],
            ]);

            //改变用户的身份
            M('User')->where(['id' => $activer['id']])->save([
                'identity' => UserModel::USER_SUPPLIER,
            ]);
            //改变申请记录状态
            $Op->where(['id' => $info['id']])->save([
                'deal_at' => time(),
                'status' => 2,
                'checker' => $this->admin_info['username'],
            ]);

            $userAccountData = [
                [
                    'user_id' => $operation['id'],
                    'amount' => $need_balance,
                    'balance' => $operation['balance'] - $need_balance,
                    'remark' => "申请下级用户【{$activer['nickname']}】成为运营中心，扣除现金{$need_balance}",
                    'created_at' => time(),
                    'type_id' => UserAccountModel::OP_CASH,
                    'source' => UserAccountModel::SC_OUT,
                ],
            ];
            if ($info['pay_type'] == 2) {
                $userAccountData[] = [
                    'user_id' => $operation['id'],
                    'amount' => $need_integral,
                    'balance' => $operation['integral'] - $need_integral,
                    'remark' => "申请下级用户【{$activer['nickname']}】成为运营中心，扣除积分{$need_integral}",
                    'created_at' => time(),
                    'type_id' => UserAccountModel::OP_INTEGRAL,
                    'source' => UserAccountModel::SC_OUT,
                ];
            }

            if (M('UserAccount')->addAll($userAccountData) === false) {
                throw new Exception(M('UserAccount')->getError());
            }

            //写入系统日志记录
            $sysAccountData = [];
            $sys_applier_data_1 = [
                'user_id' => $operation['id'],
                'amount' => $need_balance,
                'remark' => "运营中心【{$operation['nickname']}】，申请下级用户【{$activer['nickname']}】成为运营中心",
                'created_at' => time(),
                'type_id' => SysAccountModel::OP_CASH,
                'source' => SysAccountModel::OP_IN,
            ];
            if ($info['pay_type'] == 2) {
                $sysAccountData[] = [
                    'user_id' => $operation['id'],
                    'amount' => $need_integral,
                    'remark' => "运营中心【{$operation['nickname']}】，申请下级用户【{$activer['nickname']}】成为运营中心，支付{$this->setting['pay_integral_percent']}%积分{$need_integral}",
                    'created_at' => time(),
                    'type_id' => SysAccountModel::OP_INTEGRAL,
                    'source' => SysAccountModel::OP_IN,
                ];
                $sys_applier_data_1['remark'] .= "，支付{$this->setting['pay_balance_percent']}%现金{$need_balance}";
            } else {
                $sys_applier_data_1['remark'] .= "，支付现金{$need_balance}";
            }

            $sysAccountData[] = $sys_applier_data_1;
            M('SysAccount')->addAll($sysAccountData);

            //发送消息
            M('Message')->add(
                [
                    'user_id' => $activer['id'],
                    'title' => '恭喜申请通过审核',
                    'content' => "恭喜【{$activer['nickname']}】，您的运营中心身份申请已通过管理员审核",
                    'created_at' => time(),
                ]
            );

        } catch (\Exception $e) {
            M()->rollback();
            return $this->error($e->getMessage());
        }
        /**
         * 修改申请的用户身份状态，发送站内短信
         */

        M()->commit();
        $this->success('运营中心申请审核成功');
    }

    //删除申请记录
    public function delete() {
        $id = I('id', 0, 'intval');
        if (empty($id)) {
            return $this->error('缺少参数');
        }

        if (M('OperationsInfo')->where(['id' => $id])->delete() !== false) {
            return $this->success('删除成功');
        }

        return $this->error('删除失败');
    }

}
